#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Denis Kürov
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt.


from iptables.models import Loadindex
from iptables.dbwork.rulegen import IptablesRunner


class RuleLoadOrder(object):
    """ That wil handle the oprations that are concerned
    with order of the rulez"""
    
    def __init__(self):
        """ may initialize some stuff here"""
        
    
    def insert_order(self,parent_id,ordernum='last'):
        """ Inserting one the default is the end of the list"""
        try:
            
            er=Loadindex.objects.filter(parent_rule=parent_id)
            if er:
                self.delete_order(parent_id)
            
            if  ordernum !='last':
                #gets the bigger ones
                l=Loadindex.objects.filter(ordering__gte=ordernum).order_by('ordering')
                if l:
                    for index in l:
                        index.ordering+=1
                        index.save()
                    
                    #To make only one acess to database
                    toinsert=Loadindex(parent_rule_id=parent_id,ordering=ordernum)
                    toinsert.save()
                    
                    return True
                
            l2=Loadindex.objects.order_by('-ordering')[:1]
            
            if l2:
                ordering=l2[0].ordering+1
                #print ordering
                toinsert=Loadindex(parent_rule_id=parent_id,ordering=ordering)
                
            else:
                toinsert=Loadindex(parent_rule_id=parent_id,ordering=1)
            
            toinsert.save()
            
            #burada yeniden calistir olacak
            
            return True
        
        except Exception,e:
            print "Db Error Ocuured :",e
            return False


    def delete_order(self,parent_id):
        """ Deleting a order from db list that are loaded"""
        try :
            er=Loadindex.objects.filter(parent_rule=parent_id)
            if not er:
                #print "All ready exists"
                return True
            
            l=Loadindex.objects.filter(ordering__gt=er[0].ordering).order_by('ordering')
            if l:
                for index in l:
                    index.ordering-=1
                    index.save()
                    
            er[0].delete()
            
            #burada yeniden calistir olacak
            
            return True        
                
                
        except Exception ,e:
            print "Db Error Ocuured :",e
            return False
        
    def swap_order(self,first,second,chain_name=None):
        """ Swaps 2 rules first with the second.Order is very important in rule management"""
        
        try :
            #print "First swap parameter is ",first
            #print "second swap parameter is ",second
            er=Loadindex.objects.filter(parent_rule__in=[first,second]).count()
            print er
            if er!=2:      
                print "Wrong swap parameters"
                return False
            
            
            l=Loadindex.objects.filter(parent_rule__in=[first,second])
            
            #order_swap = l[0].ordering
            #l[0].ordering = l[1].ordering
            #l[1].ordering = order_swap
            l1 = l[0]
            l2 = l[1]
            
            l1.ordering,l2.ordering=l2.ordering,l1.ordering
            
            l1.save()
            l2.save()
            
            #burada flush + yeniden yukleme kismi olur 
            #aslinda buradaki flash da chain seviyesinde olablir yani evt
            
            IptablesRunner.flush_signal(chain_name=chain_name)
            
            #it must be done here yep
            
            return True
        
        except Exception,e:
            print "Db Error Ocuured :",e
            return False
        
if __name__=="__main__":
    pass
 
